package co.fitstart.weapp.api.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.DateUtils;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.weapp.api.dao.BwhRecordDao;
import co.fitstart.weapp.api.service.BwhRecordService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@Service("bwhRecordService")
public class BwhRecordServiceImpl implements BwhRecordService {

    @Dao
    private BwhRecordDao bwhRecordDao;

    @Autowired
    private GenericDaoSupport genericDaoSupport;
 
    /*
     * (non-Javadoc)
     * @see co.fitstart.weapp.api.service.BwhRecordService#list(co.fitstart.entity.course.round.CourseRound)
     */
    public List<BwhRecord> list(CourseRound courseRound) {
        return bwhRecordDao.list(courseRound);
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.weapp.api.service.BwhRecordService#listForResultReport(co.fitstart.entity.course.round.CourseRound)
     */
    public List<BwhRecord> listForResultReport(CourseRound courseRound) {
        return bwhRecordDao.listForResultReport(courseRound);
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.weapp.api.service.BwhRecordService#create(co.fitstart.entity.course.round.CourseRound, co.fitstart.entity.user.bwh.BwhRecord)
     */
    public void create(CourseRound courseRound, BwhRecord bwhRecord) {
        if(bwhRecord.getBust() == null || bwhRecord.getWaist() == null || bwhRecord.getHips() == null || bwhRecord.getWeight() == null) {
            throw new BusinessException("三围数据不能为空");
        } else if(!courseRound.getCourseType().isOnline()) {
            throw new BusinessException(courseRound.getCourseType().getOther() + "课程不能记录三围数据");
        } else {
            List<BwhRecord> bwhRecords = bwhRecordDao.list(courseRound);
            
            if(!bwhRecords.isEmpty() && DateUtils.isSameWeek(bwhRecords.get(bwhRecords.size() - 1).getCreateTime(), new Date())) {
                throw new BusinessException("线上课程一周只能记录一次三围数据");
            } else {
                genericDaoSupport.save(bwhRecord.initilization(courseRound));
            }
        }
    }

}
